package com.lagou.dao;

import com.lagou.domain.User;
import com.lagou.util.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Administrator
 */
public class UserDao {

    private User user;
    private Connection connection;

    public  UserDao(User user) {
        this.user = user;
        //获取连接
        connection = DruidUtils.getConnection();
    }

    public boolean userIsExists() throws SQLException{
        //flag
        boolean flag = false;

        //编写sql
        String sql = "select * from login_user where username = ?";

        //获取执行平台
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());

        //执行sql
        ResultSet resultSet = ps.executeQuery();
        if(resultSet.next()){
            System.out.println("用户存在");
            flag = true;
        }else{
            System.out.println("用户不存在");
        }
        return flag;
    }

    public boolean checkPassword() throws SQLException {
        //flag
        boolean flag = false;

        //编写sql
        String sql = "select password from login_user where username = ?";

        //获取执行平台
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());

        //执行sql
        ResultSet resultSet = ps.executeQuery();
        if(resultSet.next()){
            String password = resultSet.getString(1);
            System.out.println("database:" +password);
            System.out.println("输入的:" +user.getPassword());
            //判断用户名密码和数据库的密码是否一致
            if(password.equals(user.getPassword())){
                flag = true;
            }
        }
        return flag;
    }

    public boolean insertUser() throws SQLException {
        //编写sql
        String sql = "insert into login_user (username,password) values(?,?)";
        //获取执行平台
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());

        //执行sql
        int result = ps.executeUpdate();
        return result == 1;
    }
}
